package zy.jpa;

import java.util.Date;
import java.util.List;

import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
@Remote(PersonDAO.class)
public class PersonDAOBean implements PersonDAO {
	@PersistenceContext
	protected EntityManager em;

	public String getPersonNameByID(int personid) {
		Person person = em.find(Person.class, Integer.valueOf(personid));
		return person.getName();
	}

	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public void batchInsertDemoPersions() {
		clearTableDemoDatas();
		long start = System.currentTimeMillis();
		int count = 1000;
		for (int i = 0; i < count; i++) {
			this.insertPerson("黎明_" + i, true, (short) (26 + i), new Date(
					System.currentTimeMillis() + i * 24 * 60 * 60 * 1000));
		}
		System.out.println("批量插入数据" + count + "行，消耗时间="
				+ (System.currentTimeMillis() - start) / 1000 + "秒");
	}

	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public void clearTableDemoDatas() {
		Query query = em.createQuery("delete from Person");
		int delCount = query.executeUpdate();
		System.out.println("删除全部数据，累计删除" + delCount + "行");
	}

	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public boolean insertPerson(String name, boolean sex, short age,
			Date birthday) {
		try {
			Person person = new Person();
			person.setName(name);
			person.setSex(sex);
			person.setAge(Short.valueOf(age));
			person.setBirthday(birthday);
			em.persist(person);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public Person getPersonByID(int personid) {
		return em.find(Person.class, personid);
	}

	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public boolean updatePerson(Person person) {
		try {
			em.merge(person);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public List getPersonList() {
		long start = System.currentTimeMillis();
		Query query = em.createQuery("from Person order by personid asc");
		List list = query.getResultList();
		System.out.println("获取累计" + list.size() + "条记录，耗时"
				+ (System.currentTimeMillis() - start) / 1000 + "秒");
		return list;
	}
}